interface HeroData<T> {
  code: number;
  data: T;
  msg: string;
}
interface HeroItemData {
  heroId: string; // id
  name: string; // 称号
  alias: string; // 英文名
  title: string; // 中文名
  icon: string; // 头像
}

// pages/hero/hero.ts
Page({
  /**
   * 页面的初始数据
   */
  data: {
    heroList: [] as HeroItemData[],
    name: "",
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    this.getHeroData().then((res) => {
      // console.log(res);
      this.setData({
        heroList: res,
      });
    });
  },

  // 获取英雄列表
  getHeroData(heroName: string = "") {
    // 希望返回什么就给 promise 指定什么类型
    return new Promise<HeroItemData[]>((resolve, reject) => {
      wx.showLoading({ title: "拼命加载中..." });
      wx.request<HeroData<HeroItemData[]>>({
        method: "GET",
        url: "https://api-vue-base.itheima.net/api/lol/search",
        data: {
          q: heroName,
        },
        success: (res) => {
          resolve(res.data.data);
        },
        fail: () => {
          reject();
        },
        complete: () => {
          wx.hideLoading();
        },
      });
    });
  },

  // 搜索英雄
  async onSubmit() {
    console.log("输入：", this.data.name);
    const list = await this.getHeroData();
    // 非空判断
    if (!this.data.name.trim()) {
      this.setData({
        heroList: list,
        name: "",
      });
      wx.showToast({
        title: "内容不能为空",
        icon: "error",
      });
      return;
    }
    const res = await this.getHeroData(this.data.name.trim());
    // 判断查询结果是否为空
    if (res?.length > 0) {
      console.log("查询结果", res);
      this.setData({
        heroList: res,
      });
    } else {
      wx.showToast({ title: "没有搜索到英雄", icon: "error" });
      console.log("ccc", res);
      this.setData({
        heroList: list,
        name: "",
      });
    }
  },

  // 路由跳转
  goToDetails(event: any) {
    // console.log('aaaaaa',event.mark.heroId);
    wx.navigateTo({
      url: `/pages/heroDetails/heroDetails?heroId=${event.mark.heroId}`,
    });
  },
});
